<?php
namespace Destroyer;

use Illuminate\Support\Str;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Response;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;

use Destroyer\Response as AdminResponse;
use Destroyer\Models\User;

class AdminServiceProvider extends ServiceProvider
{


    /**
     * 启动服务
     */
    public function boot(): void
    {
        // $this->mergeConfigFrom(
        //     __DIR__.'/../config/rabbitmq.php',
        //     'queue.connections.rabbitmq'
        // );
        
        if (!config('admin.enabled')) {
            return;
        }

        // 注册看守器
        $this->registerGuard();

        // 注册路由
        $this->registerRoutes();

        // 语言包
        $this->loadTranslationsFrom(__DIR__.'/../lang', 'destroyer');

        Response::macro('admin', AdminResponse::success());
        Response::macro('error', AdminResponse::error());
    }

    public function registerGuard()
    {
        // 定义看守器
        Auth::viaRequest('destroyer-token', Guard::guard());

        // 配置看守器
        Config::set('auth.guards.admin', [
            'driver' => 'destroyer-token',
            'provider' => 'admin',
        ]);
        // 配置用户提供器
        Config::set('auth.providers.admin', [
            'driver' => 'eloquent',
            'model' => User::class,
        ]);
    }

    /**
     * 注册后台路由
     */
    protected function registerRoutes()
    {
        Route::middlewareGroup('admin.api', config('admin.middleware', []));
        Route::group([
            'domain' => config('admin.domain', null),
            'namespace' => 'Destroyer\Http\Controllers',
            'prefix' => config('admin.path', 'admin-api'),
            'middleware' => 'admin.api',
        ], function () {
            $this->loadRoutesFrom(dirname(__DIR__).'/routes/api.php');
        });
    }
}
